﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using ConfExpert;
using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;
using TailordDS;
using TailordDS.AppDSTableAdapters;
using DevExpress.XtraGrid.Views.Grid.Customization;

namespace Tailord
{
    public partial class XForm : DevExpress.XtraEditors.XtraForm
    {
        public int WhoAmI = -1;
        public int MyDept = -1;
        public string MyName = "";
        
        public AppDS ds = null;
        
        public Image notready = Properties.Resources.NotReadySmall;
        string adet = "Count: ";
        string toplam = "Sum: ";


        public List<CustomizationForm> CustomizationForms = new List<CustomizationForm>();

        public XForm()
        {
            InitializeComponent();


            if (AppSession.UserInfo != null)
            {
                WhoAmI = AppSession.UserInfo.UserId;
                MyDept = AppSession.UserInfo.DeptId;
                MyName = AppSession.UserInfo.Name;                
            }

            this.StartPosition = FormStartPosition.CenterParent;

            //BaseBarManager = barManager;

            ds = new AppDS();
            ds.EnforceConstraints = false;

            foreach (DataRelation rel in ds.Relations)
            {
                ForeignKeyConstraint ParentFK = new ForeignKeyConstraint(rel.ParentColumns, rel.ChildColumns);
                ParentFK.UpdateRule = Rule.Cascade;
                rel.ChildTable.Constraints.Add(ParentFK);
            }

            TAM = new TableAdapterManager();
            
        }

        public void ShowOnlyBar()
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = true;
        }

        public void ShowOnlyFooter()
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = false;
        }

        protected void EndGridViewEdit(GridView view)
        {
            view.CloseEditor();
            view.UpdateCurrentRow();
        }

        public void ExecQuery(string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                AppSession.DataManager.ExecuteNonQuery(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        public void SetGridCaption(GridView gv, string caption)
        {
            gv.OptionsView.ShowViewCaption = true;
            gv.Appearance.ViewCaption.TextOptions.HAlignment = HorzAlignment.Near;
            gv.ViewCaption = caption;
        }

          void gridview_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {

            GridView g = sender as GridView;
            DevExpress.XtraGrid.Views.Base.GridCell[] cells = g.GetSelectedCells();
            if (cells.Length == 0)
                return;

            double sum = 0;

            foreach (DevExpress.XtraGrid.Views.Base.GridCell gc in cells)
            {
                double val = 0.0;
                string cellVal = g.GetRowCellDisplayText(gc.RowHandle, gc.Column);
                CultureInfo ci = Application.CurrentCulture;
                double.TryParse(cellVal, NumberStyles.Any, ci, out val);

                sum += val;
            }

            adet = string.Format("{0}{1:n0}", "Count: ", cells.Length);

            if (sum > 0)
                toplam = string.Format("{0}{1:n1}", "Sum: ", sum);
            else
                toplam = "";

            AppSession.MainForm.NotifySelectionInfo(this);
        }
        string selectionInfo = "";
        public string SelectionInfo
        {
            get {

                string seperator = "  " + ((char)183) + "  ";
                List<string> result = new List<string>();
                
                result.Add(adet);

                if (toplam != "")
                    result.Add(toplam);

                if (selectionInfo != "")
                    result.Add(selectionInfo);

                return string.Join(seperator, result.ToArray());
            }
            set
            {
                selectionInfo = value;
                AppSession.MainForm.NotifySelectionInfo (this);
            }
        }


        
        public void InitGridView(GridView gridview, BindingSource bs, bool initialized = false)
        {
            try
            {
                gridview.GridControl.MenuManager = barManager;
                gridview.SelectionChanged -= gridview_SelectionChanged;
                gridview.SelectionChanged += gridview_SelectionChanged;
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                if (bs != null)
                {
                    gridview.GridControl.DataSource = null;
                    gridview.GridControl.DataSource = bs;
                    gridview.PopulateColumns();
                }
                if (gridview.ViewCaption == string.Empty)
                    gridview.ViewCaption = gridview.Name;

               
                foreach (GridColumn col in gridview.Columns)
                {
                    if (col.FieldName != bs.DataMember + "Id")
                        MapGridColumn(col);
                    else
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.AppearanceCell.BackColor = System.Drawing.Color.LightYellow;
                    }

                    if (col.ColumnType == Type.GetType("System.Boolean"))
                    {
                        RepositoryItemCheckEdit ri = new RepositoryItemCheckEdit();
                        ri.AllowGrayed = false;
                        col.ColumnEdit = ri;
                    }
                    else if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }
                    else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;
                }
                 
                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                gridview.NewItemRowText = "Click to add new row";
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                //gridview.OptionsBehavior.EditorShowMode = AppSession.Settings.EditorShowMode;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                //gridview.OptionsView.EnableAppearanceEvenRow = AppSession.Settings.EnableAppearanceEvenRow;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }
                GridManager.GetManager(gridview);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }
        }

        void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName == "Scan" || e.Column.FieldName == "PhotoMikro") &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 16), e.Bounds.Y);
                    e.Handled = true;
                }
        }

        void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.RowHeight < notready.Height)
                    e.RowHeight = notready.Height;
        }

        public void MapGridColumn(GridColumn col)
        {
            string fieldName = col.FieldName;

            col.FilterMode = ColumnFilterMode.DisplayText;
            //You can change the filter condition in the OptionsColumn.AutoFilterCondition property for every column in GridView.
            //col.OptionsFilter.AutoFilterCondition = (AppSession.Settings.PopupFilterMode == PopupFilterMode.Contains ? AutoFilterCondition.Contains : AutoFilterCondition.Default);    // AutoFilterCondition.Contains;

            //col.OptionsColumn.AllowEdit = col.FieldName != "UserId";    //userId sonradan değiştirilemesin diye!

            if (col.ColumnType == typeof(String))
                col.ColumnEdit = new RepositoryItemTextEdit();

            switch (fieldName)
            {
                case "deleted":
                case "temp":
                case "ınsertedon":
                case "modifiedon":
                case "ts": col.Visible = false; break;

                default:
                    if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(0);
                    else if (";fiyat;hedeffiyat;anlasilanfiyat;xanlasilanfiyat;faturafiyati;xfaturafiyati;birimfiyat;unitprice;latestunitprice;price;price_;cost;balance;linetotal;subtotal;discount;grandtotal;taxamt;freight;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(2);

                    break;
            }
        }
        
      
         

        public void CenterGridColumn(GridColumn col)
        {
            col.AppearanceCell.Options.UseTextOptions = true;
            col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
        }

        public RepositoryItem RI(Rp repository)
        {
            return RepositoryManager.Get(repository);
        }

        public RepositoryItem GetFieldRI(string fieldName)
        {

            fieldName = fieldName.ToLower();

            if (fieldName.EndsWith("Id".ToLower()))
            {
                fieldName = fieldName
                                        .Substring(0, fieldName.Length - 2)
                                        .Replace("latest", "")
                                        .Replace("prf", "");
                switch (fieldName)
                {
                    case "cari": return RI(Rp.Cari);
                    case "kaynak": return RI(Rp.Kaynak);
                    case "cember": return RI(Rp.Cember);
                    case "sticker": return RI(Rp.Sticker);
                    case "yakaalti": return RI(Rp.Yakaalti);
                    case "addresstype": return RI(Rp.AddressType);

                    case "atelye":
                    case "cikisyeri": return RI(Rp.Atelye);

                    case "belgetipi":
                    case "belgetipialis": return RI(Rp.BelgeTipiAlis);

                    case "belgetipisatis": return RI(Rp.BelgeTipiSatis);
                    case "carrier": return RI(Rp.Carrier);
                    case "contact": return RI(Rp.V_Contact);
                    case "contacttype": return RI(Rp.ContactType);
                    case "country": return RI(Rp.Country);

                    case "currency":
                    case "hedefcurrency":
                    case "dvz":
                    case "xdvz":
                    case "faturadvz":
                    case "xfaturadvz":
                    case "dovizcinsi": return RI(Rp.Currency);

                    case "culture": return RI(Rp.Culture);
                    case "origin": return RI(Rp.Origin);

                    //case "malsahibi":
                    ////case "owner":
                    //case "kcustomer":
                    //case "customer":
                    //    //RepositoryItemGridLookUpEdit gle =(RepositoryItemGridLookUpEdit) RI(Rp.V_Customer);
                    //    //gle.TextEditStyle = TextEditStyles.Standard;
                    //    return RI(Rp.V_Customer);

                    case "teslimseklis": return RI(Rp.TeslimSekliS);
                    case "department": return RI(Rp.Department);

                    case "sender":
                    case "user":
                    case "cikanuser":
                    case "cikan":
                    case "employee":
                    case "duzenleyen":
                    case "talepeden":
                    case "talebiacan":
                    case "sipveren":
                    case "siparişeden":
                    case "sipariseden":
                    case "sorumlu":
                    case "olusturan":
                    case "onaylayan":
                    case "planlamaci":
                    case "odeyen": return RI(Rp.V_User);


                    case "bedenetiketi": return RI(Rp.BedenEtiketi);
                    case "gruppotex": return RI(Rp.GruppoTex);

                    case "giristipi":
                    case "cikistipi":
                    case "harekettipi": return RI(Rp.HareketTipi);

                    case "depo": return RI(Rp.Depo);
                    case "model": return RI(Rp.Model);
                    case "module": return RI(Rp.Module);

                    case "marka":
                    case "brand":
                    case "newbrand":
                    case "onaylayacak": return RI(Rp.Brand);

                    case "paymentterm": return RI(Rp.PaymentTerm);
                    case "paymentmethod": return RI(Rp.PaymentMethodA);
                    case "paymentmethoda": return RI(Rp.PaymentMethodA);
                    case "paymentmethods": return RI(Rp.PaymentMethodS);
                    case "productcategory": return RI(Rp.ProductCategory);

                    case "product":
                    case "product1":
                    case "product2":
                    case "product3":
                    case "product4":
                    case "subst":
                    case "subst1":
                    case "subst2":
                    case "subst3":
                    case "alt":
                    case "org":
                    case "alternatif":
                    case "silinecek":
                    case "kalacak":
                    case "esp":
                    case "kumas": return RI(Rp.V_Kumas);

                    case "aksesuar": return RI(Rp.Aksesuar);
                    case "tela": return RI(Rp.Tela);
                    case "telavendor": return RI(Rp.TelaVendor);
                    case "telacins": return RI(Rp.TelaCins);
                    case "telafinish": return RI(Rp.TelaFinish);
                    case "raporboyu": return RI(Rp.RaporBoyu);
                    case "salesagent": return RI(Rp.V_SalesAgent);

                    case "mt":
                    case "musteritemsilcisi":
                    case "salesperson": return RI(Rp.V_SalesPerson);

                    case "teamleader": return RI(Rp.V_TeamLeader);

                    case "sezon":
                    case "newsezon": return RI(Rp.Sezon);

                    case "reqshipmethod":
                    case "revshipmethod":
                    case "shipmethod": return RI(Rp.ShipMethod);

                    case "durum1":
                    case "sipdurumu1": return RI(Rp.SiparisDurumu1);

                    case "durum2":
                    case "sipdurumu2":
                    case "siparisdurumu": return RI(Rp.SiparisDurumu2);

                    case "yuklemesekli":
                    case "ongorulenyuklemesekli":
                    case "xongorulenyuklemesekli":
                    case "maxongorulenyuklemesekli":
                    case "gerceklesenyuklemesekli":
                    case "xgerceklesenyuklemesekli":
                    case "ongyuklemesekli":
                    case "revyuklemesekli":
                    case "geryuklemesekli": return RI(Rp.YuklemeSekli);

                    case "teslimsekli":
                    case "ongteslimsekli":
                    case "gerteslimsekli":
                    case "faturadakiteslimsekli":
                    case "xteslimsekli":
                    case "xfaturadakiteslimsekli":
                    case "teslimseklia": return RI(Rp.TeslimSekliA);

                    case "deporaf":
                   // case "shelf": return RI(Rp.Shelf);
                    case "shelftela": return RI(Rp.ShelfTela);
                    case "stoktipi": return RI(Rp.StokTipi);
                    case "unitmeasure": return RI(Rp.UnitMeasure);

                    case "productionvendor":
                    case "latestvendor":
                    case "orgvendor":
                    case "kvendor":
                    //case "vendor":
                    case "tercihedilenuretici":
                    case "orjinaluretici":
                    case "uretici":
                    case "gelisyeri":
                    case "akstedarikci": return RI(Rp.Vendor);

                    case "kullanimyeri": return RI(Rp.KullanimYeri);
                    case "dagilim": return RI(Rp.Dagilim);
                    case "modelcategory": return RI(Rp.ModelCategory);
                    case "modelsubcategory": return RI(Rp.ModelSubcategory);
                    case "kalite": return RI(Rp.Kalite);
                    case "sttalep": return RI(Rp.stTalep);
                    case "taleptipi": return RI(Rp.TalepTipi);
                    case "stsiparis": return RI(Rp.stSiparis);
                    case "stcikis": return RI(Rp.stCikis);
                    case "stfatura": return RI(Rp.stFatura);
                    //case "stgenel": return RI(Rp.stGenel); TODO: 
                    case "sturetim": return RI(Rp.stUretim);
                    case "stkesim": return RI(Rp.stKesim);
                    case "engrubu": return RI(Rp.EnGrubu);
                    case "finish": return RI(Rp.Finish);

                    case "zeminrengi":
                    case "desenrengi": return RI(Rp.TemelRenk);

                    case "desen": return RI(Rp.Desen);
                    case "orgu": return RI(Rp.Orgu);
                    case "desenyonu": return RI(Rp.DesenYonu);
                    case "stokgrup": return RI(Rp.StokGrup);
                    case "grup7c": return RI(Rp.Grup7C);
                    case "grupesp": return RI(Rp.GrupESP);
                    case "stgeribildirim": return RI(Rp.stGeriBildirim);
                    case "geribildirimıletituru": return RI(Rp.GeriBildirimIletiTuru);
                    case "stap": return RI(Rp.stAP);
                    case "apyuklemesekli": return RI(Rp.apYuklemeSekli);
                    case "apnavlunsekli": return RI(Rp.apNavlunSekli);
                    case "apakreditifturu": return RI(Rp.apAkreditifTuru);
                    case "apodemesuresigun": return RI(Rp.apOdemeSuresiGun);
                    case "kompozisyon": return RI(Rp.Kompozisyon);
                    case "konstruksiyon": return RI(Rp.Konstruksiyon);
                    case "ytalimat": return RI(Rp.YTalimat);

                    case "terms":
                    case "priceterm": return RI(Rp.PriceTerm);

                    case "scenario": return RI(Rp.Scenario);
                    case "fabrictype": return RI(Rp.FabricType);
                    case "hata": return RI(Rp.Hata);
                    case "kstcategory": return RI(Rp.KstCategory);

                    case "stirsaliye":
                    case "stırsaliye": return RI(Rp.stIrsaliye);

                    case "robaetiketi": return RI(Rp.RobaEtiketi);
                    case "klips": return RI(Rp.Klips);
                    case "prdtree": return RI(Rp.PrdTree);
                    case "ckbatch": return RI(Rp.CKBatch);
                    case "kalitekontrol": return RI(Rp.KaliteKontrol);
                    case "kumashatatipi": return RI(Rp.KumasHataTipi);
                    case "sevkiyatci": return RI(Rp.Sevkiyatci);
                    default: return null;
                }
            }
            else
            {
                switch (fieldName)
                {
                    case "photomikro":
                        return RepositoryManager.GetPhotoRI();

                    default:
                        if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        {
                            return new RepositoryItemCalcEdit();
                        }
                        return null;
                }
            }
        }

        public void GetDetails(string SemiColonSeperatedTableNames, string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                AppDS dsNew = (AppDS)AppSession.DataManager.Fill(new AppDS(), SemiColonSeperatedTableNames, SP, prm);

                ds.Merge(dsNew, false, MissingSchemaAction.AddWithKey);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        public static void SetSplitterPosition(SplitContainerControl scc)
        {
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public virtual void MySizeChanged(object sender, EventArgs e)
        {
            //SplitContainerControl scc = ((SplitContainerControl)sender);
            //scc.SizeChanged -= sizeChanged;
            SetSplitterPosition(sender as SplitContainerControl);
            //scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public List<BindingSource> sources;
        public void EndEdits()
        {
            this.Validate();
            if (sources != null)
                foreach (BindingSource bs in sources)
                    bs.EndEdit();
        }
        
        public int ChangesSubmitted = 0;
        public TableAdapterManager TAM;
        public virtual void Save()
        {
            EndEdits();
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Notify("Saving...");

                if (ds.HasChanges())
                    ChangesSubmitted += TAM.UpdateAll(ds);
            }
            catch (DBConcurrencyException ex)
            {
                ConcurrencySolver cs = new ConcurrencySolver(ex.Row);
                DialogResult response = cs.ShowDialog();

                switch (response)
                {
                    case DialogResult.OK:
                        GetDetails(ex.Row.Table.TableName, "UpdConfilict", cs.Sql);
                        try
                        {
                            Save();
                        }
                        catch (Exception saveEx)
                        {
                            LogManager.LogToDB(cs.Log + response.ToString());
                            throw saveEx;
                        }
                        LogManager.LogToDB(cs.Log + response.ToString());
                        break;
                    case DialogResult.Cancel:
                        LogManager.LogToDB(cs.Log + response.ToString());
                        throw new ApplicationException("Değişiklikler KAYDEDİLMEDİ !!!");
                }

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
                Notify(string.Empty);
            }
        }

        public static void Notify(string str)
        {
            ConfExpert.Utility.AppSession.MainForm.NotifyMain(str);
        }
 

        private void XForm_Load(object sender, EventArgs e)
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = false;          
            this.FormClosing += new FormClosingEventHandler(XForm_FormClosing);
            bbiHideDeleted.CheckedChanged += bbiHideDeleted_CheckedChanged;
        }

        public virtual void bbiHideDeleted_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //throw new NotImplementedException();
        }

      

        public virtual void XForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            AppSession.MainForm.SetActiveXFormFromMDIManager();
            ds.Dispose();
        }

        public RepositoryItemGridLookUpEdit GetCustomRI(string caption, bool createRuntimeID, params string[] items)
        {
            string valueMember = caption;

            DataTable dataSource = new DataTable();

            dataSource.Columns.Add("Id", typeof(int));
            dataSource.Columns.Add(caption, typeof(string));

            for (int i = 0; i < items.Length; i++)
                dataSource.Rows.Add(new object[] { i + 1, items[i] });

            if (createRuntimeID)
                valueMember = "Id";
            else
                dataSource.Columns.RemoveAt(0);

            return RepositoryManager.GetGLESablon(dataSource, caption, valueMember);
        }

        public RepositoryItemGridLookUpEdit GetCustomGLE(DataTable dt, string displayMember, string valueMember)
        {
            RepositoryItemGridLookUpEdit ri = RepositoryManager.GetGLESablon(dt, displayMember, valueMember);
            ri.View.Columns.Clear();

            int visibleindex = 0;
            foreach (DataColumn column in dt.Columns)
            {
                string caption = column.Caption;
                if (caption != "TS" && caption != "Deleted" && caption != "ModifiedOn")
                {
                    GridColumn col = ri.View.Columns.AddField(caption);

                    col.VisibleIndex = visibleindex++;
                    col.Caption = caption;
                }
            }

            ri.TextEditStyle = TextEditStyles.DisableTextEditor;
            return ri;
        }

        public void AddBsToList(params BindingSource[] bsElement)
        {
            sources = new List<BindingSource>(bsElement.Length);
            foreach (BindingSource bs in bsElement)
                sources.Add(bs);
        }

        public List<int> EnabledBarcodeTypes = new List<int>();
        public void EnableBarcodeType(params int[] Types)
        {
            foreach (int type in Types)
                EnabledBarcodeTypes.Add(type);
        }

        public delegate void BarcodeReadHandler(int Type, int Barcode);
        public event BarcodeReadHandler BarcodeRead;


        public void FireBarcodeRead(int Type, int Barcode)
        {
            if (BarcodeRead != null)
                this.BeginInvoke(new BarcodeReadHandler(BarcodeRead), new object[] { Type, Barcode });
        }
    }
}